<%@page import="java.util.UUID"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/pages/common/taglib.jsp"%>
<%
	String uuid = UUID.randomUUID().toString();
	request.setAttribute("uuid", uuid);
%>

<div class="box box-primary">
	<div class="row">
		<div class="col-md-3" id="dataModelGroup_${uuid}">
			<div class="box-header with-border">
				<h3 class="box-title">
				</h3>
				<div class="box-tools pull-right">
				</div>
			</div>
			<div class="box-body">
			
			</div>
		</div>
		<div class="col-md-9">
			<div class="box-header with-border">
				<h3 class="box-title">
					
				</h3>
				<div class="box-tools pull-right" id="tableDefGridTB_${uuid}">
					<shiro:hasPermission name="FRM_DEF_ADD">
						<div class="btn-group">
							<button type="button" class="btn btn-sm btn-success addBtn">
								<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
								添加
							</button>
							<button type="button" class="btn btn-sm btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
								<span class="caret"></span>
								<span class="sr-only"></span>
							</button>
							<ul class="dropdown-menu">
								<li>
									<a href="javascript:void(0)" class="addBtn">填写新增表单</a>
								</li>
								<li>
									<a href="javascript:void(0)" class="selectPhyBtn">选择已有的表</a>
								</li>
							</ul>
						</div>
					</shiro:hasPermission>

					<shiro:hasPermission name="FRM_DEF_MOD">
						<button class="btn btn-sm btn-primary editBtn">
							<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
							修改
						</button>
					</shiro:hasPermission>

					<shiro:hasPermission name="FRM_DEF_DEL">
						<button type="button" class="btn btn-sm btn-danger delBtn">
							<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
							删除
						</button>
					</shiro:hasPermission>

					<shiro:hasPermission name="FRM_DEF_BUILD">
						<div class="btn-group">
							<button type="button" class="btn btn-sm btn-default buildTableBtn">
								<span class="glyphicon glyphicon-leaf" aria-hidden="true"></span>
								生成物理表
							</button>
							<button type="button" class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
								<span class="caret"></span>
								<span class="sr-only"></span>
							</button>
							<ul class="dropdown-menu">
								<li>
									<a href="javascript:void(0)" class="buildTableBtn">生成物理表</a>
								</li>
								<li>
									<a href="javascript:void(0)" class="rebuildTableBtn">重新生成</a>
								</li>
							</ul>
						</div>
					</shiro:hasPermission>
					
					<shiro:hasPermission name="FRM_DEF_BUILD">
						<div class="btn-group">
							  <button type="button" class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							   	 交换 <span class="caret"></span>
							  </button>
							  <ul class="dropdown-menu">
							    <li><a href="javascript:void(0)" class="expBtn">导出</a></li>
							    <li><a href="javascript:void(0)" class="impBtn" id="impDataModelDefBtn">导入</a></li>
							  </ul>
						</div>
					</shiro:hasPermission>
				</div>
			</div>
			<div class="box-body">
				<table id="tableDefGrid_${uuid}"></table>
			</div>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-md-12">
		<div class="nav-tabs-custom">
			<ul class="nav nav-tabs" role="tablist">
				<li class="active">
					<a href="#fieldDefGridTab_${uuid}" data-toggle="tab">
						<span class="glyphicon glyphicon-paperclip"></span>
						字段定义
					</a>
				</li>
				<li>
					<a href="#eventDefTab_${uuid}" data-toggle="tab">
						<span class="glyphicon glyphicon-exclamation-sign"></span>
						事件定义
					</a>
				</li>
			</ul>
			<div class="tab-content">
				<div class="tab-pane active" id="fieldDefGridTab_${uuid}">
					<div class="box-header with-border">
						<h3 class="box-title"></h3>
						<!-- /.box-title -->
						<div class="box-tools pull-right" id="fieldDefGridTB_${uuid}">
							<shiro:hasPermission name="FRM_FIELD_DEF_ADD">
								<button class="btn btn-sm btn-success addBtn">
									<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
									添加
								</button>
							</shiro:hasPermission>

							<shiro:hasPermission name="FRM_FIELD_DEF_MOD">
								<button class="btn btn-sm btn-primary editBtn">
									<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
									修改
								</button>
							</shiro:hasPermission>

							<shiro:hasPermission name="FRM_FIELD_DEF_DEL">
								<button class="btn btn-sm btn-danger delBtn">
									<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
									删除
								</button>
							</shiro:hasPermission>
						</div>
					</div>
					<!-- /.box-header -->
					<div class="box-body">
						<table id="fieldDefGrid_${uuid}"></table>
					</div>
					<!-- /.box-body -->
				</div>
				<div class="tab-pane" id="eventDefTab_${uuid}">
					<form role="form" id="tableOptEventDefFrom_${uuid}">
						<input type="hidden" name="id">
						<input type="hidden" name="dataModelId">

						<div class="box-header with-border">
							<h3 class="box-title"></h3>
							<!-- /.box-title -->
							<div class="box-tools pull-right" id="fieldDefGridTB_${uuid}">
								<shiro:hasPermission name="FRM_OPTEVENT_DEF_SAVE">
									<a href="javascript:void(0);" class="btn btn-sm btn-success addBtn">
										<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
										保存
									</a>
								</shiro:hasPermission>

								<shiro:hasPermission name="FRM_OPTEVENT_DEF_DEL">
									<a href="javascript:void(0);" class="btn btn-sm btn-danger delBtn">
										<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
										注销
									</a>
								</shiro:hasPermission>
							</div>
						</div>
						<!-- box-header -->
						<div class="box-body">
							<div class="form-group">
								<input type="text" class="form-control" placeholder="spring bean name" name="beanName">
							</div>

							<h1 class="page-header">使用说明</h1>
							<ol>
								<li>
									<p>实现com.wiseMen.dataModel.def.dataEvent.DataEventInterceptor接口</p>
								</li>
								<li>
									<p>befoceSave方法：在保存前触发，如果返回false，则不执行保存方法</p>
								</li>
								<li>
									<p>befoceAdd方法：在insert方法前，在befoceSave后触发。 前提是befoceSave返回true。 如果befoceAdd方法返回false，则不执行insert方法。</p>
								</li>
								<li>
									<p>befoceUpdate方法：在update方法前，在befoceSave后触发。 前提是befoceSave返回true。 如果befoceUpdate方法返回false，则不执行update方法。</p>
								</li>
								<li>
									<p>afterSave方法：在保存成功后触发。</p>
								</li>
								<li>
									<p>afterAdd方法：在insert成功后触发。</p>
								</li>
								<li>
									<p>afterUpdate方法：在update成功后触发。</p>
								</li>
								<li>
									<p>执行顺序如下befoceSave -> befoceAdd/befoceUpdate ->afterAdd/afterUpdate ->afterSave。</p>
								</li>
								<li>
									<p>FormTableDefineEntity参数：表单定义实体，内有表单定义、字段定义列表</p>
								</li>
								<li>
									<p>FormTableData参数：用户提交表单时的数据，已对主子表关联字段进行处理</p>
								</li>
								<li>
									<p>Map&#60;String,FormFieldData&#62;&nbsp;form参数：实际需要保存到数据库中的值，其中包括一些用户、组织机构、创建时间等必要字段</p>
								</li>
							</ol>
						</div>
						<!-- /.box-body -->
					</form>
				</div>
			</div>

		</div>
		<!-- /.nav-tabs-custom -->
	</div>
</div>
<script type="text/javascript">
	$(function() {
		var uuid = '${uuid}';
		var dataModelGroup;
		var _tableDefGridTB = $("#tableDefGridTB_" + uuid);
		require([ 'wiseMen/dataModel/dataModelGroup' ],
				function(DataModelGroup) {
					dataModelGroup = new DataModelGroup({
						render : $("#dataModelGroup_" + uuid),
						onClick : function(treeNode) {
							tableDefGrid.dataModelGroupCode = treeNode.code;
							tableDefGrid.bootstrapTable("refresh");
						}
					});
				});

		var tableDefGrid = $("#tableDefGrid_" + uuid)
				.bootstrapTable(
						{
							columns : [
									{
										field : '_id',
										checkbox : true
									},
									{
										title : '模型标识',
										field : 'code',
										width : '80px',
										orderable : true
									},
									{
										title : '名称',
										field : 'name',
										width : '120px'
									},
									{
										title : '存储方式',
										field : 'storageMode',
										width : '120px',
										formatter : function(value,row, index) {
											return webUtils.getDataDicItemVal(
													"DM_STORAGE_MODE", value).name;
										}
									},
									{
										title : '已生成',
										field : 'hasBuilt',
										width : '40px',
										formatter : function(value,row, index) {
											if (value == 1) {
												return "是";
											} else {
												return "否";
											}
										}
									} ],
									url : ctx + "/dataModelDefAct/queryDefs.do",
									queryParams:function(d){
										if (tableDefGrid) {
											if (tableDefGrid.dataModelGroupCode) {
												d.dataModelGroupCode = tableDefGrid.dataModelGroupCode;
											}
										}
										return d;
						        	},
						        	onClickRow:function(row){
						        		var id = row.id;
						    			fieldDefGrid.dataModelId = id;
						    			fieldDefGrid.bootstrapTable("refresh");

						    			loadDataEvent(id);
						        	}
						});

		/* 添加按钮事件 */
		_tableDefGridTB
				.find(".addBtn")
				.click(
						function() {
							if (tableDefGrid.dataModelGroupCode) {
								var sub = top.webUtils.topicSubscribe(
										"tableDefine.edit.success", function(
												args) {
											dialog.close();
											tableDefGrid.bootstrapTable("refresh");
										});
								var dialog = editTableDefine({
									dataModelGroupCode : tableDefGrid.dataModelGroupCode,
									onClose : function() {
										sub.remove();
									}
								});
							} else {
								webUtils.error("请选择具体的业务分组");
							}
						});
		/* 修改按钮事件 */
		_tableDefGridTB.find(".editBtn").click(
				function() {
					var rows = tableDefGrid.bootstrapTable("getSelections");
					if (rows && rows.length > 0) {
						var sub = top.webUtils.topicSubscribe(
								"tableDefine.edit.success", function(args) {
									dialog.close();
									tableDefGrid.bootstrapTable("refresh");
								});
						var row = rows[0];
						var dialog = editTableDefine({
							id : row.id,
							onClose : function() {
								sub.remove();
							}
						});
					} else {
						webUtils.alert("请选择需要编辑的数据");
					}
				});

		/* 删除按钮事件 */
		_tableDefGridTB.find(".delBtn").click(function() {
			var rows = tableDefGrid.bootstrapTable("getSelections");
			if (rows && rows.length > 0) {
				webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if (result) {
						var selecteds = [];
						$.each(rows, function(i, n) {
							selecteds.push(n.id);
						});
						$.post(ctx + "/dataModelDefAct/delDefs.do", {
							ids : selecteds.join(",")
						}, function(data) {
							if (data.success) {
								webUtils.alert("操作成功");
								tableDefGrid.bootstrapTable("refresh");
							} else {
								webUtils.alert(data.msg);
							}
						}, 'json');
					}
				})

			} else {
				webUtils.alert("请选择需要删除的数据");
			}
		});

		/* 只删除定义信息 */
		_tableDefGridTB.find(".delTableDefInfoBtn").click(function() {
			var rows = tableDefGrid.bootstrapTable("getSelections");
			if (rows && rows.length > 0) {
				webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if (result) {
						var selecteds = [];
						$.each(rows, function(i, n) {
							selecteds.push(n.id);
						});
						$.post(ctx + "/dataModelDefAct/delDefInfos.do", {
							ids : selecteds.join(",")
						}, function(data) {
							if (data.success) {
								webUtils.alert("操作成功");
								tableDefGrid.bootstrapTable("refresh");
							} else {
								webUtils.alert(data.msg);
							}
						}, 'json');
					}
				});

			} else {
				webUtils.alert("请选择需要删除的数据");
			}
		});

		/* 只删除物理表  */
		_tableDefGridTB.find(".delTablePhyInfoBtn").click(function() {
			var rows = tableDefGrid.bootstrapTable("getSelections");
			if (rows && rows.length > 0) {
				webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if (result) {
						var selecteds = [];
						$.each(rows, function(i, n) {
							selecteds.push(n.id);
						});
						$.post(ctx + "/dataModelDefAct/delPhyInfos.do", {
							ids : selecteds.join(",")
						}, function(data) {
							if (data.success) {
								webUtils.alert("操作成功");
								tableDefGrid.bootstrapTable("refresh");
							} else {
								webUtils.alert(data.msg);
							}
						}, 'json');
					}
				});

			} else {
				webUtils.alert("请选择需要删除的数据");
			}
		});

		/*
			生成表结构
		 */

		_tableDefGridTB.find(".buildTableBtn").click(function() {
			var rows = tableDefGrid.bootstrapTable("getSelections");
			if (rows && rows.length > 0) {
				var row = rows[0];
				if (row.hasBuilt == 1) {
					webUtils.alert("该表已生成，不可重复该操作");
				} else {
					$.post(ctx + "/dataModelDefAct/buildToPhy.do", {
						id : row.id
					}, function(data) {
						if (data.success) {
							tableDefGrid.bootstrapTable("refresh");
							webUtils.alert("成功生成库表！");
						} else {
							webUtils.error(data.msg);
						}
					}, 'json');
				}

			} else {
				webUtils.alert("请选择需要生成库表的数据");
			}
		});

		/* 从源有的物理表中获取  */
		_tableDefGridTB.find(".selectPhyBtn").click(function() {
			alert("暂时未提供该功能。");
		});
		/* 导入导出 */
		_tableDefGridTB.find(".expBtn").click(function(){
        	var rows=tableDefGrid.bootstrapTable("getSelections");
        	if(rows && rows.length>0){
        		var ids = [];
                $.each(rows, function (i, n) {
                	ids.push(n.id);
                });
        		window.open(ctx + "/dataModelDefAct/export.do?ids="+ids.join(","));
        	} else {
        		webUtils.alert("请选择需要导出的数据");
            }
        });
        
        var dataModelUploader
        webUtils.fileUploader({
        	server:ctx+"/dataModelDefAct/import.do",
        	uploadPick:"#impDataModelDefBtn",
        	duplicate:false,
        	accept: {
                title: 'json文件类型',
                extensions: 'json'
            },
            afterInit:function(u,uder){
            	dataModelUploader=u;
            },
            uploadBeforeSend:function(object , data ,headers){
            	data.dataModelGroupCode=tableDefGrid.dataModelGroupCode;
            }
        });
        
        _tableDefGridTB.find(".impBtn").mouseenter(function(){
        	dataModelUploader.refresh();
        });

		var editTableDefine = function(params) {
			params = params || {};
			var p = [];
			if (params.id) {
				p.push("id=" + params.id);
			}
			if (params.dataModelGroupCode) {
				p.push("dataModelGroupCode=" + params.dataModelGroupCode);
			}

			var dialog = webUtils.dialog({
				title : '编辑模型定义',
				url : ctx + '/dataModelDefAct/editView.do?' + p.join("&"),
				onremove : function() {
					if (params.onClose) {
						params.onClose.call(null);
					}
				}
			});
			return dialog;
		}

		//---------------------------
		var fieldDefGrid = $("#fieldDefGrid_" + uuid)
				.bootstrapTable(
						{
							columns : [
{field: '_id',checkbox:true},
									{
										title : '字段',
										field : 'code',
										width : '80px',
										orderable : false
									},
									{
										title : '中文名',
										field : 'name',
										width : '220px',
										orderable : false
									},
									{
										title : '类型',
										field : 'type',
										width : '100px',
										formatter:function(value, type, row,
												meta) {
											var dicItem = webUtils
													.getDataDicItemVal(
															"TABLE_DEF_FIELD_TYPE",
															value);
											if (dicItem) {
												return dicItem.name;
											}
										},
										orderable : false
									},
									{
										title : '长度',
										field : 'size',
										width : '60px',
										formatter:function(value,row, index) {
											if (row.fieldType == "number") {
												return "(" + row.size + ","
														+ row.scale + ")";
											} else {
												return row.size;
											}
										},
										orderable : false
									},
									{
										title : '必填',
										field : 'isRequired',
										width : '60px',
										formatter:function(value,row, index) {
											return value == 1 ? "√" : "";
										},
										orderable : false
									},
									{
										title : '排序',
										field : 'sn',
										width : "80",
										formatter:function(value,row, index) {
											var html = '<a class="btn btn-link btn-sm _j_upBt" data-id="'+row.id+'" data-index="'+value+'">'
													+ '<span class="glyphicon glyphicon-chevron-up"></span>'
													+ '</a>'
													+ '<a class="btn btn-link btn-sm _j_downBt"  data-id="'+row.id+'" data-index="'+value+'">'
													+ '<span class="glyphicon glyphicon glyphicon-chevron-down"></span>'
													+ '</a>';
											return html;
										}
									} ],
									url : ctx + "/dataModelFieldDefAct/query.do",
									queryParams:function(d){
										if (fieldDefGrid
												&& fieldDefGrid.dataModelId) {
											d.dataModelId = fieldDefGrid.dataModelId;
										} else {
											d.dataModelId = -1;
										}

										return d;
						        	},
						        	onLoadSuccess : function() {
								$("#fieldDefGrid_" + uuid).find("._j_upBt")
										.click(function() {
											_this = $(this);
											var id = _this.data("id");
											var index = _this.data("index");
											sort(id, index, "goUp");
										});
								$("#fieldDefGrid_" + uuid).find("._j_downBt")
										.click(function() {
											_this = $(this);
											var id = _this.data("id");
											var index = _this.data("index");
											sort(id, index, "goDown");
										});
							}
						});

		function sort(id, index, action) {
			$.post(ctx + "/dataModelFieldDefAct/sort.action", {
				id : id,
				action : action,
				index : index
			}, function(data) {
				if (data.success) {
					fieldDefGrid.bootstrapTable("refresh");
				} else {
					webUtils.alert(data.msg);
				}
			}, "json");
		}

		var _fieldDefGridTB = $("#fieldDefGridTB_" + uuid);
		_fieldDefGridTB.find(".addBtn").click(
				function() {
					if (fieldDefGrid.dataModelId) {
						var sub = top.webUtils.topicSubscribe(
								"fieldDefine.edit.success", function(args) {
									dialog.close();
									fieldDefGrid.bootstrapTable("refresh");
								});
						var dialog = editFieldDefine({
							dataModelId : fieldDefGrid.dataModelId,
							onClose : function() {
								sub.remove();
							}
						});
					} else {
						webUtils.alert("请选择具体的表定义");
					}
				});
		_fieldDefGridTB.find(".editBtn").click(
				function() {
					var rows = fieldDefGrid.bootstrapTable("getSelections");
					if (rows && rows.length > 0) {
						var sub = top.webUtils.topicSubscribe(
								"fieldDefine.edit.success", function(args) {
									dialog.close();
									fieldDefGrid.bootstrapTable("refresh");
								});
						var row = rows[0];
						var dialog = editFieldDefine({
							id : row.id,
							onClose : function() {
								sub.remove();
							}
						});
					} else {
						webUtils.alert("请选择需要编辑的数据");
					}
				});
		_fieldDefGridTB.find(".delBtn").click(function() {
			var rows = fieldDefGrid.bootstrapTable("getSelections");
			if (rows && rows.length > 0) {
				webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if (result) {
						var selecteds = [];
						$.each(rows, function(i, n) {
							selecteds.push(n.id);
						});
						$.post(ctx + "/dataModelFieldDefAct/delByIds.do", {
							ids : selecteds.join(",")
						}, function(data) {
							if (data.success) {
								fieldDefGrid.bootstrapTable("refresh");
							} else {
								webUtils.alert(data.msg);
							}
						}, 'json');
					}
				});

			} else {
				webUtils.alert("请选择需要删除的数据");
			}
		});

		var editFieldDefine = function(params) {
			params = params || {};
			var p = [];
			if (params.id) {
				p.push("id=" + params.id);
			}
			if (params.dataModelId) {
				p.push("dataModelId=" + params.dataModelId);
			}

			var dialog = webUtils.dialog({
				title : '编辑字段定义',
				url :ctx + '/dataModelFieldDefAct/editView.do?'+ p.join("&"),
				onremove : function() {
					if (params.onClose) {
						params.onClose.call(null);
					}
				}
			});
			return dialog;
		}

		var _tableOptEventDefFrom = $("#tableOptEventDefFrom_" + uuid);
		_tableOptEventDefFrom.find(".addBtn").click(
				function() {
					var beanName = _tableOptEventDefFrom.find(
							"input[name=beanName]").val();
					var dataModelId = _tableOptEventDefFrom.find(
							"input[name=dataModelId]").val();
					if (!dataModelId) {
						webUtils.error("请选择具体的模型");
						return false;
					}
					if (!beanName) {
						webUtils.error("请输入bean名称");
						return false;
					}
					_tableOptEventDefFrom.ajaxSubmit({
						url : ctx + '/dataEventAct/save.do',
						data : {},
						type : "POST",
						success : function(data) {
							if (data.success) {
								webUtils.alert("提交成功");
							} else {
								webUtils.error(data.msg);
							}
						}
					});
				});
		_tableOptEventDefFrom.find(".delBtn").click(
				function() {
					var beanName = _tableOptEventDefFrom
							.find("input[name=beanName]");
					var dataModelId = _tableOptEventDefFrom
							.find("input[name=dataModelId]");
					$.post(ctx + "/dataEventAct/delByDataModelId.do", {
						dataModelId : dataModelId.val()
					}, function(data) {
						if (data.success) {
							beanName.val("");
						} else {
							webUtils.alert(data.msg);
						}
					}, 'json');
				});

		var loadDataEvent = function(dataModelId) {
			var data = {
				id : "",
				dataModelId : dataModelId,
				beanName : ""
			};
			webUtils.fullForm({
				form : _tableOptEventDefFrom,
				data : data
			});
			$.getJSON(ctx + '/dataEventAct/findByDataModelId.do', {
				dataModelId : dataModelId
			}, function(data) {
				webUtils.fullForm({
					form : _tableOptEventDefFrom,
					data : data
				});
			});
		}

	});
</script>